package controllers

import (
	"github.com/astaxie/beego"
	"helloCms/models"
	"github.com/astaxie/beego/orm"
	"time"
	"strings"
	"strconv"
)

type UserInfoController struct {
	beego.Controller
}

type searchUserInfo struct {
	pageIndex int
	pageSize int
	name string
	remark string
	count int64
}

func (c *UserInfoController) Index() {
	c.TplName = "UserInfo/Index.html"
}

func (s *searchUserInfo)searchUser() []models.Userinfo {
	o:=orm.NewOrm()
	temp:=o.QueryTable("userinfo").Filter("del_flag", 0)
	if s.name!=""{
		temp=temp.Filter("user_name__icontains",s.name)
	}
	if s.remark!=""{
		temp=temp.Filter("remark__icontains",s.remark)
	}
	s.count,_=temp.Count()
	start := (s.pageIndex - 1) * s.pageSize
	users:=make([]models.Userinfo, 0)
	temp.OrderBy("Id").Limit(s.pageSize,start).All(&users)
	return users
}

func (c *UserInfoController) GetUserInfo() {
	pageIndex, _ := c.GetInt("page")
	pageSize, _ := c.GetInt("rows")
	name:=c.GetString("name")
	remark:=c.GetString("remark")

	targetUser:=searchUserInfo{
		pageIndex:pageIndex,
		pageSize:pageSize,
		name:name,
		remark:remark,
	}
	users:=targetUser.searchUser()

	c.Data["json"] = map[string]interface{}{"rows": users, "total": targetUser.count}
	c.ServeJSON()
}

func (c *UserInfoController) DeleteUser()  {
	ids:=strings.Split(c.GetString("id"),",")
	//beego.Info(ids)
	o:=orm.NewOrm()
	user:=models.Userinfo{}
	for _,id:=range ids{
		user.Id,_=strconv.Atoi(id)
		o.Read(&user)
		user.DelFlag=1
		o.Update(&user)
	}
	c.Data["json"]=map[string]interface{}{"flag":"ok"}
	c.ServeJSON()
}

func (c *UserInfoController) AddUser() {
	userInfo := models.Userinfo{
		UserName:  c.GetString("UserName"),
		UserPwd:   c.GetString("UserPwd"),
		Remark:    c.GetString("Remark"),
		ModifDate: time.Now(),
		AddDate:   time.Now(),
		DelFlag:   0,
	}

	o:=orm.NewOrm()
	_,err:=o.Insert(&userInfo)
	if err==nil{
		c.Data["json"]=map[string]interface{}{"flag":"ok"}
	}else {
		c.Data["json"]=map[string]interface{}{"flag":"no"}
	}
	c.ServeJSON()


}

func (c *UserInfoController)EditUser()  {
	id:=c.GetString("id")
	//beego.Info(id)
	id2,err:=strconv.Atoi(id)
	if err!=nil{
		beego.Info("获取修改用户ID失败")
		return
	}
	user:=models.Userinfo{Id:id2}
	o:=orm.NewOrm()
	o.Read(&user)
	user.ModifDate=time.Now()
	user.UserName=c.GetString("UserName")
	user.UserPwd=c.GetString("UserPwd")
	user.Remark=c.GetString("Remark")
	//beego.Info(user)
	o.Update(&user)

	c.Data["json"]=map[string]interface{}{"flag":"ok"}
	c.ServeJSON()
}

func (c *UserInfoController)ShowSetUserRole()  {
	o:=orm.NewOrm()

	user:=models.Userinfo{}
	id,_:=c.GetInt("id")
	user.Id=id
	o.Read(&user)

	allRoles:=make([]models.Roleinfo,0)
	o.QueryTable("roleinfo").Filter("del_flag", 0).All(&allRoles)
	//beego.Info(allRoles)

	userRole:=make([]models.Roleinfo,0)
	o.LoadRelated(&user,"Roles")
	for _,v:=range user.Roles{
		userRole=append(userRole,*v)
	}
	//beego.Info(userRole)


	c.Data["user"]=user
	c.Data["allRoles"]=allRoles
	c.Data["userRole"]=userRole
	c.TplName="UserInfo/ShowSetUserRole.html"
}

func (c *UserInfoController)EditUserRole()  {
	userId,_:=c.GetInt("id")

	allKeys:=c.Ctx.Request.PostForm
	//beego.Info(allKeys)
	roleIdList:=make([]int,0)

	for k,_:=range allKeys{//获取checkbox选中的角色ID
		if strings.Contains(k,"cba_"){
			k=strings.Replace(k,"cba_","",-1)
			id,_:=strconv.Atoi(k)
			roleIdList=append(roleIdList,id)
		}
	}
//beego.Info(roleIdList)
	o:=orm.NewOrm()
	user:=models.Userinfo{Id:userId}
	o.LoadRelated(&user,"Roles")  //读取多对多信息
	m2m:=o.QueryM2M(&user,"Roles")//开启多对多事务

	o.Begin()//开启事务
	var (
		err1 error
		err2 error
	)
	for _,v:=range user.Roles{
		_,err1=m2m.Remove(v) //删除用户已有的多对多关系
	}
	role:=models.Roleinfo{}
	for _,v:=range roleIdList{
		o.QueryTable("roleinfo").Filter("Id",v).One(&role)
		_,err2=m2m.Add(role)
	}
	if err1!=nil||err2!=nil{
		o.Rollback()//回滚事务
		c.Data["json"]=map[string]interface{}{"flag":"no"}
	}else {
		c.Data["json"]=map[string]interface{}{"flag":"ok"}
	}
	o.Commit()//提交事务
	c.ServeJSON()
}

func (c *UserInfoController)ShowUserAction()  {
	userId,_:=c.GetInt("userId")

	o:=orm.NewOrm()
	userInfo:=models.Userinfo{Id:userId}
	o.Read(&userInfo)
	userExtActions:=make([]models.Useraction,0)//用户已有的权限
	o.QueryTable("useraction").Filter("users_id",userId).All(&userExtActions)
	allActions:=make([]models.Actioninfo,0)
	o.QueryTable("actioninfo").Filter("del_flag",0).All(&allActions)

	c.Data["userInfo"]=userInfo
	c.Data["allActions"]=allActions
	c.Data["userExtActions"]=userExtActions
	c.TplName="UserInfo/ShowSetUserAction.html"
}

func (c *UserInfoController)SetUserAction()  {
	userId,_:=c.GetInt("userId")
	actionId,_:=c.GetInt("actionId")
	isPass,_:=c.GetInt("isPass")
	userAction:=models.Useraction{}

	o:=orm.NewOrm()
	o.QueryTable("useraction").Filter("users_id",userId).Filter("actions_id",actionId).One(&userAction)
	//表中有可能存在userAction，也有可能不存在，要分两种情况,存在的话直接修改isPass，不存在要Insert

	if userAction.Id>0{//大于0表示存在
		userAction.IsPass=isPass
		_,err:=o.Update(&userAction)
		if err!=nil{
			beego.Info(err)
			c.Data["json"]=map[string]interface{}{"flag":"no"}
		}
	}else {
		userInfo:=models.Userinfo{Id:userId}
		o.Read(&userInfo)
		actionInfo:=models.Actioninfo{Id:actionId}
		o.Read(&actionInfo)

		userAction.Users=&userInfo
		userAction.Actions=&actionInfo
		userAction.IsPass=isPass

		_,err:=o.Insert(&userAction)
		if err!=nil{
			beego.Info(err)
			c.Data["json"]=map[string]interface{}{"flag":"no"}
		}else {
			c.Data["json"]=map[string]interface{}{"flag":"ok"}
		}
	}
	c.ServeJSON()
}

func (c *UserInfoController)DeleteUserAction()  {
	userId,_:=c.GetInt("userId")
	actionId,_:=c.GetInt("actionId")
	userAction:=models.Useraction{}

	o:=orm.NewOrm()
	o.QueryTable("useraction").Filter("users_id",userId).Filter("actions_id",actionId).One(&userAction)
	_,err:=o.Delete(&userAction)
	if err!=nil{
		beego.Info(err)
		c.Data["json"]=map[string]interface{}{"flag":"no"}
	}else {
		c.Data["json"]=map[string]interface{}{"flag":"ok"}
	}
	c.ServeJSON()
}